package com.qiangesoft.ai.tongyi.service.impl;

import com.alibaba.cloud.ai.tongyi.audio.TongYiAudioSpeechClient;
import com.alibaba.cloud.ai.tongyi.audio.api.SpeechPrompt;
import com.alibaba.cloud.ai.tongyi.audio.api.SpeechResponse;
import com.alibaba.cloud.ai.tongyi.chat.TongYiChatClient;
import com.alibaba.cloud.ai.tongyi.image.TongYiImagesClient;
import com.qiangesoft.ai.tongyi.service.TongYiService;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.nio.ByteBuffer;
import java.util.Base64;

/**
 * 通义AI服务层
 *
 * @author qiangesoft
 * @date 2024-10-10
 */
@Service
public class TongYiServiceImpl implements TongYiService {

    @Autowired
    private TongYiChatClient tongYiChatClient;

    @Autowired
    private TongYiImagesClient tongYiImagesClient;

    @Autowired
    private TongYiAudioSpeechClient tongYiAudioSpeechClient;

    @Override
    public String answer(String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        ChatResponse chatResponse = tongYiChatClient.call(prompt);
        return chatResponse.getResult().getOutput().getContent();
    }

    @Override
    public Flux<ChatResponse> streamAnswer(String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        return tongYiChatClient.stream(prompt);
    }

    @Override
    public byte[] genImg(String message) {
        ImagePrompt imagePrompt = new ImagePrompt(message);
        ImageResponse imageResponse = tongYiImagesClient.call(imagePrompt);
        String b64Json = imageResponse.getResult().getOutput().getB64Json();
        return Base64.getDecoder().decode(b64Json);
    }

    @Override
    public byte[] genAudio(String message) {
        SpeechPrompt speechPrompt = new SpeechPrompt(message);
        SpeechResponse speechResponse = tongYiAudioSpeechClient.call(speechPrompt);
        ByteBuffer byteBuffer = speechResponse.getResult().getOutput();
        return byteBuffer.array();
    }

}